package com.ksyun.cloudhostalarmprocessing.controller;

import com.ksyun.cloudhostalarmprocessing.common.*;
import com.ksyun.cloudhostalarmprocessing.entity.Metrics;
import com.ksyun.cloudhostalarmprocessing.entity.vo.MetricsDataVO;
import com.ksyun.cloudhostalarmprocessing.entity.vo.MetricsVO;
import com.ksyun.cloudhostalarmprocessing.entity.vo.RateVO;
import com.ksyun.cloudhostalarmprocessing.service.IMetricsService;
import com.ksyun.cloudhostalarmprocessing.service.Impl.ElasticsearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 李厚航
 * @since 2024-05-07
 */
@RestController
@RequestMapping("/metric")
public class MetricsController {

    @Resource
    private IMetricsService metricsService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ElasticsearchService elasticsearchService;
    @PostMapping("/put")
    @CrossOrigin
    public Response put(@RequestBody List<Request> requests){
        metricsService.add(requests);
        return Response.ok();
    }

    @GetMapping("/count")
    @CrossOrigin
    public ResultSet getCount(){

        Integer count = metricsService.selectCount();
        return ResultSet.ok(count);
    }

    @GetMapping("/get/{page}/{size}")
    @CrossOrigin
    public ResultSet get(@PathVariable("page")Integer page, @PathVariable("size") Integer size) {
        Integer start  = (page - 1) * size;
        List<Metrics> metricsVOS = metricsService.selectAll(start,size).stream().sorted(Comparator.comparing(Metrics::getTimestamp)).collect(Collectors.toList());
        List<List<Metrics>> result = new ArrayList<>();
        List<Metrics> subgroup = new ArrayList<>();

        for (int i = 0; i < metricsVOS.size(); i++) {
            // 每22个对象构成一个小列表
            if (i % 22 == 0 && i != 0) {
                result.add(subgroup);
                subgroup = new ArrayList<>();  // 创建新的小列表
            }
            subgroup.add(metricsVOS.get(i));
        }
        result.add(subgroup);

        return ResultSet.ok(result);
    }

    @CrossOrigin
    @PostMapping("/query")
    public QueryResponse<MetricsDataVO> query(@RequestBody QueryRequest queryRequest){
        return metricsService.getByTimestamp(queryRequest);
    }

    @GetMapping()
    public ResultSet addData() throws IOException {
        elasticsearchService.bulkImport();
        return ResultSet.ok();
    }

}
